package com.ruoyi.finance.protal.utils;


import com.ruoyi.finance.protal.shandpay.cashier.sdk.CertUtil;
import com.ruoyi.finance.protal.shandpay.cashier.sdk.CryptoUtil;
import com.ruoyi.finance.protal.shandpay.cashier.sdk.HttpClient;
import com.ruoyi.finance.protal.shandpay.cashier.sdk.SDKUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : SignUtil
 * @Description :
 * @Author : Wcl
 * @DateTime : 2023/7/23 12:59
 * @Since JDK1.8.0_251
 **/
public class SignUtil {
    private static String charset = "UTF-8";

    private static final Logger logger = LoggerFactory.getLogger(SignUtil.class);

    public static String signAndReq(String url,String data,String extend) throws Exception {
        //加载证书
        try {
           CertUtil.init(DynamicPropertyHelper.getStringProperty("sandpay.public.key", "").get(), DynamicPropertyHelper.getStringProperty("sandpay.private.key", "").get(),DynamicPropertyHelper.getStringProperty("sandpay.private.key.password", "").get());
        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] dataBytes = data.getBytes("UTF-8");
        //签名
        String sign = new String(
                Base64.encodeBase64(CryptoUtil.digitalSign(dataBytes, CertUtil.getPrivateKey(), "SHA1WithRSA")),
                "UTF-8");
        //组装参数
        Map<String, String> reqMap = new HashMap<String, String>();
        //整体报文格式
        reqMap.put("charset","UTF-8"); //编码方式
        reqMap.put("signType","01"); //签名方式 代表SHA1+RSA
        reqMap.put("data", data); //交易报文
        reqMap.put("sign", sign); // 签名
        reqMap.put("extend", extend); // 扩展域


        //发起请求
        String result;
        try {
            logger.info("最终请求报文：\n" + reqMap);
            result = HttpClient.doPost(url, reqMap,10000, 10000);
            result = URLDecoder.decode(result, charset);
        } catch (IOException e) {
            logger.error(e.getMessage());
            return null;
        }
        //将解码后的响应报转换为map
        Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);

        String respData = respMap.get("data");
        logger.info("响应data："+respData);
        String respSign = respMap.get("sign");
        logger.info("响应sign："+respSign);
        byte[] respDataBytes = new byte[0];
        try {
            respDataBytes = respData.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            logger.error("不支持的字符编码"+e.getMessage());
            e.printStackTrace();
        }

        byte[] signDataBytes = Base64.decodeBase64(respSign);

        //加载杉德公钥
        PublicKey publicKey = CertUtil.getPublicKey();
        //验签
        boolean isValid = false;
        try {
            isValid = CryptoUtil.verifyDigitalSign(respDataBytes, signDataBytes, publicKey,
                    "SHA1WithRSA");
        } catch (Exception e) {
            logger.error("验签失败："+e.getMessage());
            e.printStackTrace();
        }
        if (!isValid) {
            logger.error("响应报文验签不通过");
        }else {
            logger.info("响应报文验签通过");
        }
        return respData;
    }



}
